package com.zqwh.xtool.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hwit.HwitManager;
import com.zqwh.xtool.R;
import com.zqwh.xtool.domain.LendInfo;
import com.zqwh.xtool.domain.LendItem;
import com.zqwh.xtool.domain.LentData;
import com.zqwh.xtool.enums.StockStatus;
import com.zqwh.xtool.utils.ZqwhUtils;
import com.zqwh.yj.sdk.model.InventoryListener;
import com.zqwh.yj.sdk.utils.CommonUtils;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.StringUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.RetrofitSingleton;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;
import com.zqwh.yj.sdk.widget.adapterrv.CommonAdapter;
import com.zqwh.yj.sdk.widget.adapterrv.ViewHolder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.zqwh.xtool.ToolsApp.gContext;
import static com.zqwh.xtool.ToolsApp.gDevId;
import static com.zqwh.xtool.ToolsApp.gLendOrderModel;
import static com.zqwh.xtool.ToolsApp.gProfile;
import static com.zqwh.xtool.ToolsApp.gRfidModel;
import static com.zqwh.xtool.ToolsApp.gStockModel;
import static com.zqwh.xtool.ToolsApp.gUser;

public class LendReturnActivity extends BaseActivity{
    protected static final int STATUS_IDLE = 100;
    protected static final int STATUS_DATA_LOADED = 200;
    protected static final int STATUS_OPENED = 300;
    protected static final int STATUS_INVENTORY_ING = 400;
    protected static final int STATUS_INVENTORY_END = 500;

    private RecyclerView rvTools;
    private TextView tvTitle;
    private LinearLayout llLoading;
    private TextView tvLoadingContent;
    private TextView tvInventory;
    private TextView tvConfirm;
    private TextView tvOvertime;
    private TextView tvLendNumber;
    private TextView tvReturnNumber;
    private TextView tvOwingNumber;
    private TextView tvTotalNumber;
    private TextView tvTimer;

    private List<LendItem> allList = new ArrayList<>();
    private List<LendItem> returnList;
    private List<LendItem> lendList;
    private List<LendItem> owingList;
    private List<LendItem> illegalTagList;
    private List<LendItem> illegalToolList;
    private CommonAdapter<LendItem> adapterStock;

    private String epcs;
    private List<String> currentEpcList = new ArrayList<>();
    private int status = STATUS_IDLE;

    private Timer timerOver;
    private int timerCount = 30;
    private boolean runTimer = true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lend_return_box);

        setView();
        setClickListener();

        getLentOrderDetailList();
        getStocks();
        startDetectDoorStatus();
        startOverTimer();
    }

    private void startOverTimer() {
        tvTimer.setVisibility(View.VISIBLE);
        timerOver = new Timer(true);
        timerOver.schedule(new TimerTask() {
            public void run() {
                if (runTimer) {
                    timerCount--;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (timerCount == 0) {
                                submitLendReturnOrder();
                            }else {
                                tvTimer.setText(timerCount + "秒后自动提交");
                            }
                        }
                    });
                }
            }
        },1000, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDetectDoorStatus();
        if (timerOver != null){
            timerOver.cancel();
        }
        lock();
    }

    @Override
    protected void onDoorOpened() {
        super.onDoorOpened();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogUtils.logout("开箱");
                runTimer = false;
                tvTimer.setVisibility(View.GONE);
                tvOvertime.setVisibility(View.GONE);
                if (status == STATUS_INVENTORY_ING){
                    cancelInventory();
                    if (returnList != null) {
                        returnList.clear();
                    }
                    if (lendList != null) {
                        lendList.clear();
                    }
                    produceData();
                }
                status = STATUS_OPENED;
            }
        });
    }

    @Override
    protected void onDoorClosed() {
        super.onDoorClosed();
        status = STATUS_INVENTORY_ING;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                runTimer = true;
                timerCount = 30;
                tvTimer.setVisibility(View.VISIBLE);
                LogUtils.logout("关箱");
                rfidInventory();
            }
        });
    }

    private void produceData() {
        allList.clear();
        if (lendList != null){
            allList.addAll(lendList);
        }
        if (returnList != null) {
            allList.addAll(returnList);
        }
        if (owingList != null){
            allList.addAll(owingList);
        }
        if (illegalToolList != null){
            allList.addAll(illegalToolList);
        }
        if (illegalTagList != null){
            allList.addAll(illegalTagList);
        }
    }

    private void setView() {
        rvTools = findViewById(R.id.rv_tools);
        tvTitle = findViewById(R.id.tv_title);
        tvInventory = findViewById(R.id.tv_inventory);
        tvConfirm = findViewById(R.id.tv_confirm);
        llLoading = findViewById(R.id.ll_loading);
        tvOvertime = findViewById(R.id.tv_overtime);
        tvLoadingContent = findViewById(R.id.tv_loading_content);
        tvLendNumber = findViewById(R.id.tv_lend_number);
        tvReturnNumber = findViewById(R.id.tv_return_number);
        tvOwingNumber = findViewById(R.id.tv_owing_number);
        tvTotalNumber = findViewById(R.id.tv_total_number);
        tvTimer = findViewById(R.id.tv_timer);
        tvTitle.setText("操作人："+gUser.getName());
        setRecyclerView();
    }

    private void setClickListener() {
        tvInventory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rfidInventory();
            }
        });

        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitLendReturnOrder();
            }
        });
    }

    private void setRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvTools.setLayoutManager(layoutManager);
        rvTools.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapterStock = new CommonAdapter<LendItem>(this, R.layout.item_lend_return_box, allList) {
            @Override
            protected void convert(ViewHolder holder, final LendItem lendItem, final int position) {
                if (lendItem.getSelected() == null || !lendItem.getSelected()){
                    holder.setBackgroundColor(R.id.ll_bg, getResources().getColor(R.color.colorWhite));
                }else {
                    holder.setBackgroundColor(R.id.ll_bg, getResources().getColor(R.color.color_green_200));
                }
                holder.setText(R.id.tv_stock_no, lendItem.getStockNo());
                holder.setText(R.id.tv_tool_name, lendItem.getToolName());
                if (lendItem.getUserName() == null){
                    holder.setText(R.id.tv_borrower_name, "--");
                } else {
                    holder.setText(R.id.tv_borrower_name, lendItem.getUserName());
                }
                if (lendItem.getStatus().equals(StockStatus.LEND)){
                    holder.setText(R.id.tv_status, "领用");
                    holder.setTextColor(R.id.tv_status, getResources().getColor(R.color.color_light_blue_300));
                }else if (lendItem.getStatus().equals(StockStatus.RETURN)){
                    holder.setText(R.id.tv_status, "归还");
                    holder.setTextColor(R.id.tv_status, getResources().getColor(R.color.color_green_300));
                }else if (lendItem.getStatus().equals(StockStatus.OWING)){
                    holder.setText(R.id.tv_status, "待还");
                    holder.setTextColor(R.id.tv_status, getResources().getColor(R.color.color_red_300));
                }else if (lendItem.getStatus().equals(StockStatus.ILLEGAL_TAG)){
                    holder.setText(R.id.tv_status, "非法标签");
                    holder.setTextColor(R.id.tv_status, getResources().getColor(R.color.color_red_600));
                }else if (lendItem.getStatus().equals(StockStatus.ILLEGAL_TOOL)){
                    holder.setText(R.id.tv_status, "非法工具");
                    holder.setTextColor(R.id.tv_status, getResources().getColor(R.color.color_red_600));
                }
            }
        };
        rvTools.setAdapter(adapterStock);
    }

    private void getStocks() {
        showLoading("正在加载数据...");
        gStockModel.getStock(gDevId, true, false, new NetCallback<List<LendItem>>() {
            @Override
            public void onSuccess(List<LendItem> lendItems) {
                hideLoading();

                allList.addAll(lendItems);

                for (LendItem item : allList) {
                    item.setStatus(StockStatus.IN_STOCK);
                    item.setSelected(false);
                }
                adapterStock.notifyDataSetChanged();
                unlock();
            }

            @Override
            public void onError(String msg) {
                LogUtils.error("error : "+msg);
                hideLoading();
            }
        });
    }

    private void getLentOrderDetailList() {
        showLoading("正在加载数据...");
        gLendOrderModel.getOwingStock(gDevId, gUser.getUserId(), new NetCallback<LentData>() {
            @Override
            public void onSuccess(LentData lendItems) {
                status = STATUS_DATA_LOADED;
                hideLoading();

                owingList = lendItems.getOwingItems();
                for (LendItem lendItem : owingList) {
                    lendItem.setStatus(StockStatus.OWING);
                }

                tvOwingNumber.setText(String.valueOf(owingList.size()));
                tvTotalNumber.setText(String.valueOf(lendItems.getStockTotalNum()));
            }

            @Override
            public void onError(String msg) {
                hideLoading();
            }
        });
    }

    protected void rfidInventory() {
        if (_getDoorStatus() == gProfile.getLOCK_OPEN_LEVEL()){
            showToast("请先关闭工具箱");
            return;
        }
        lock();
        tvTotalNumber.setText(String.valueOf(0));

        showLoading("正在盘点...");
        LogUtils.logout("Inventory time : "+ gProfile.getRFID_INVENTORY_TIME());
        LogUtils.logout("开始盘点");
        int ret = gRfidModel.startInventoryTag(gProfile.getRFID_INVENTORY_TIME(), new InventoryListener() {
            @Override
            public void onInventoryTagFinish(List<String> lsTagList) {
                LogUtils.logout("盘点到时结束");
                status = STATUS_INVENTORY_END;

                hideLoading();
                currentEpcList.clear();
                currentEpcList.addAll(lsTagList);
                List<String> epcList = ZqwhUtils.removeCount(lsTagList);
                epcs = CommonUtils.listToString(epcList);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshList();
                    }
                });
            }

            @Override
            public void onInventoryChanged(final int tagCount, final String epc, int antId) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (owingList != null) {
                            for (LendItem item : owingList) {
                                if (item.getEpc() != null && item.getEpc().equals(epc)) {
                                    item.setStatus(StockStatus.RETURN);
                                }
                            }
                            tvTotalNumber.setText(String.valueOf(tagCount));
//                            adapterStock.notifyDataSetChanged();
                        }
                    }
                });
            }

            @Override
            public void onInventoryOnce(String epc, int antId) {

            }

            @Override
            public void onInventoryTick(int tickCount, final int tagCount) {

            }


            @Override
            public void onInventoryError(String errMsg) {
                ToastUtils.showLongToast(gContext, errMsg);
            }
        });
        LogUtils.logout("ret : "+ret);
        if (ret != 0){
            inventoryDelay();
        }
    }

    private void inventoryDelay(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.logout("尝试重新盘点");
                        rfidInventory();
                    }
                });
            }
        }, 1000);
    }

    private void refreshList(){
        showLoading("正在更新数据...");
        gLendOrderModel.getPreSubmitInfo(gDevId, gUser.getUserId(), epcs, new NetCallback<LendInfo>() {
            @Override
            public void onSuccess(LendInfo lendInfo) {
                hideLoading();
                returnList = lendInfo.getReturnItems();
                for (LendItem lendItem : returnList) {
                    lendItem.setStatus(StockStatus.RETURN);
                }

                lendList = lendInfo.getLendItems();
                for (LendItem lendItem : lendList) {
                    lendItem.setStatus(StockStatus.LEND);
                }

                owingList = lendInfo.getOwingItems();
                for (LendItem lendItem : owingList) {
                    lendItem.setStatus(StockStatus.OWING);
                }

                illegalToolList = lendInfo.getIllegalTools();
                for (LendItem lendItem : illegalToolList){
                    lendItem.setStatus(StockStatus.ILLEGAL_TOOL);
                }

                illegalTagList = new ArrayList<>();
                for (String epc : lendInfo.getIllegalEpcs()) {
                    LendItem lendItem = new LendItem();
                    lendItem.setStatus(StockStatus.ILLEGAL_TAG);
                    lendItem.setEpc(epc);
                    lendItem.setToolName(epc);
                    illegalTagList.add(lendItem);
                }

                produceData();
                adapterStock.notifyDataSetChanged();

                tvReturnNumber.setText(String.valueOf(returnList.size()));
                tvLendNumber.setText(String.valueOf(lendList.size()));
                tvOwingNumber.setText(String.valueOf(owingList.size()));
            }

            @Override
            public void onError(String msg) {
                hideLoading();
            }
        });
    }

    private void cancelInventory(){
        hideLoading();
        LogUtils.logout("开箱取消盘点");
        gRfidModel.stopInventoryTag();
    }

    private void submitLendReturnOrder() {
        if (_getDoorStatus() == gProfile.getLOCK_OPEN_LEVEL()){
            showToast("请先关闭工具箱");
            return;
        }

        if ((returnList == null || returnList.size() == 0)
                && (lendList == null || lendList.size() == 0)
                && (illegalTagList == null || illegalTagList.size() == 0)
                && (illegalToolList == null || illegalToolList.size() == 0)){
            finish();
            startActivity(new Intent(LendReturnActivity.this, FinishActivity.class));
            return;
        }

        showLoading("正在提交数据...");
        gLendOrderModel.submitLendReturnOrder(gDevId, gUser.getUserId(), epcs, new NetCallback<Object>() {
            @Override
            public void onSuccess(Object o) {
                status = STATUS_IDLE;
                hideLoading();
                finish();
                startActivity(new Intent(LendReturnActivity.this, FinishActivity.class));
            }

            @Override
            public void onError(String msg) {
                showToast("提交失败，"+msg);
            }
        });
    }

    private void showToast(String content){
        //maketext决定Toast显示内容
        Toast toastCenter = Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG);
        //setGravity决定Toast显示位置
        toastCenter.setGravity(Gravity.CENTER,0,0);
        //调用show使得toast得以显示
        toastCenter.show();
    }

    private void showLoading(String content){
        llLoading.setVisibility(View.VISIBLE);
        if (!StringUtils.isEmpty(content)){
            tvLoadingContent.setText(content);
        }
        tvInventory.setEnabled(false);
        tvConfirm.setEnabled(false);
    }

    private void hideLoading(){
        llLoading.setVisibility(View.GONE);
        tvInventory.setEnabled(true);
        tvConfirm.setEnabled(true);
    }
}
